package com.dongline.test;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.apache.zookeeper.server.watch.WatcherMode;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class SimpleZkClient {

    private static final String connectString="192.168.1.21:2181,192.168.1.22:2181,192.168.1.23:2181";//链接字符串，各个节点的ip端口号
    private static final  int sessionTimeout=200000;//会话超时时间

    private static ZooKeeper zooKeeper;


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException, NoSuchAlgorithmException {
        zooKeeper=new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent.toString());
                try {
                    //这里设置监听为true，重复监听
                    zooKeeper.getChildren("/",true);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
         List<String> strs=zooKeeper.getChildren("/",null);
         for(String str : strs )
         {
             System.out.println(str);
         }
        // TODO Auto-generated method stub
        //new一个acl
        List<ACL> acls = new ArrayList<ACL>();
        //添加第一个id，采用用户名密码形式
        Id id1 = new Id("digest",
                DigestAuthenticationProvider.generateDigest("admin:admin"));
        ACL acl1 = new ACL(ZooDefs.Perms.ALL, id1);
        acls.add(acl1);
        //添加第二个id，所有用户可读权限
        Id id2 = new Id("world", "anyone");
        ACL acl2 = new ACL(ZooDefs.Perms.READ, id2);
        acls.add(acl2);
        zooKeeper.create("/app3",new String("123").getBytes(StandardCharsets.UTF_8),acls, CreateMode.CONTAINER);

        Thread.sleep(1000000000);
    }


}
